package Util;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 读取word脚注内容
 */
public class WordExtractFootnote {

    public static void wordExtractFootnote(String filePath,String savePath) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        HWPFDocument doc = new HWPFDocument(fis);
        BufferedWriter bw = new BufferedWriter(new FileWriter(savePath));
        // 获取文档范围
        Range range = doc.getRange();
        //存放大纲名称
        String OutlineName = null;
        String temp = null;

        // 遍历所有段落
        for (int i = 0; i < range.numParagraphs(); i++) {
            Paragraph paragraph = range.getParagraph(i);
            String style = paragraph.getStyleIndex() == -1 ? null : doc.getStyleSheet().getStyleDescription(paragraph.getStyleIndex()).getName();
            String text = paragraph.text();

            if (style != null) {
                if (style.equals("MycosCaption")) {
                    OutlineName = text;
//                    如果该段落为脚注内容则将前一个大纲内容和脚注内容一起放入txt文档文档中
                } else if (style.equals("MycosNote")&&i!=0) {
                    if (OutlineName.equals(temp)){
                        System.out.println(text);
                        bw.write("</p><p>"+text.trim());
                    }else {
                        bw.newLine();
                        temp=OutlineName;
                        bw.write(OutlineName.trim()+" "+text.trim());
                        System.out.println();
                        System.out.println(OutlineName);
                        System.out.println(text);
                    }
                }
            }
            // 关闭流

            doc.close();
            fis.close();
        }
        bw.flush();
        bw.close();
    }
}